const {nowTime,emptyData,fileterTime} = require("../utils/misc")
const ObjectId = require('mongodb').ObjectId
const router = require('koa-router')();
const mongo = require('../compents/mongo')
const {postLogData} =require("../utils/misc")
router.prefix('/activityinfo')


router.get('/list', async ctx => {
    postLogData("请求活动信息")
    let { page,startTime,endTime,name,stu_id } = ctx.query
    let where={name,stu_id},fileterData={}
    // 判断是否传值 未传值直接删除对象
    name?"":delete where.name
    stu_id?"":delete where.stu_id
    let res = await mongo.find('activityinfo', {where,limit:10000})
    startTime?(endTime?fileterData=fileterTime(res,{startTime,endTime,page}):""):""
    let total = res.length
    if(JSON.stringify(fileterData)!="{}"){
        res=fileterData.arr
        total=fileterData.total
    }
    if (res) {
        ctx.body = { data: res, code: 20000, total, message: "数据请求成功" }
    } else {
        ctx.body = {data:res, code: 50001, message: "数据请求失败" }
    }
})

router.post('/save', async ctx => {
    postLogData("保存活动信息")
    let stuData = ctx.request.body
    stuData= emptyData(stuData,["name","tel","entryFee","state","payTime","ac_id","gender","stu_id"])
    const res = await mongo.insertOne('activityinfo', { ...stuData,uploadTime:nowTime()})
    if (res.insertedId) {
        ctx.body = { data: res, code: 20000, message: "数据插入成功" };
    } else {
        ctx.body = { data: res, code: 50002, message: "数据插入失败" };
    }
})

// 修改数据库
router.post('/change', async ctx => {
    postLogData("修改活动信息")
    const { _id } = ctx.request.body
    const update = ctx.request.body
    delete update._id
    const res = await mongo.updateOne('activityinfo', { where: { _id: ObjectId(_id) }, update })
    if (res.modifiedCount > 0) {
        ctx.body = { data: res, code: 20000, message: "数据修改成功" };
    } else {
        ctx.body = { data: res, code: 50004, message: "数据修改失败" };
    }
})

// 删除数据
// 删除单挑数据
router.get('/delOne', async ctx => {
    postLogData("单删活动信息")
    const { _id } = ctx.query
    const res = await mongo.deleteOne('activityinfo', { _id: ObjectId(_id) })
    if (res.deletedCount > 0) {
        ctx.body = { data: res, code: 20000, message: "数据删除成功" };
    } else {
        ctx.body = { data: res, code: 50005, message: "数据删除失败" };
    }
})
// 删除多条数据  
router.get('/delMany', async ctx => {
    postLogData("多删活动信息")
    let { ids } = ctx.query
    ids = JSON.parse(ids)
    const res = await mongo.deleteMany('activityinfo', ids)
    if (res.deletedCount > 0) {
        ctx.body = { data: res, code: 20000, message: "数据批量删除成功" };
    } else {
        ctx.body = { data: res, code: 50006, message: "数据批量删除失败" };
    }
})
module.exports = router 